<?php
/**--------------------
 * Date: 2018/2/1
 * FileName:Knowledge.php 知识升级
 * ProjectName:ZhiShiRongYao
 * -------------------- */


namespace app\api\controller;


use app\api\ApiBase;
use think\Db;

class Knowledge extends ApiBase
{
    /**
     * 获取用户科目升级数据
     *
     * @throws \think\exception\DbException 数据库报错
     * @return string
     */
    public function getSubjectList()
    {

        //用户科目等级
        $user_level = Db::name('user_knowledge_up u')
                        ->field('subject_id,u.level')
                        ->where('user_id', $this->user_info['id'])
                        ->select();

        //所有科目
        $subject_list = Db::name('knowledge_subject s')
                          ->field('id,name,logo,parent_id')
                          ->select();

        //用户(科目)知识书
        $user_goods = Db::name('user_goods')
                        ->alias('u')
                        ->field('num,subject_id')
                        ->join('prop p', 'p.id=u.target_id')
                        ->where([
                                    'target_type' => 2,
                                    'type'        => 4,
                                    'user_id'     => $this->user_info['id']
                                ])
                        ->select();

        $goods = [];
        if ($user_goods) {
            foreach ($user_goods as $good) {
                $goods[$good['subject_id']] = $good;
            }
        }

        //等级限制
        $rule  = Db::name('knowledge_up_rule')
                   ->field('level,up_num,up_point')
                   ->select();
        $rules = [];
        if ($rule) {
            foreach ($rule as $ru) {
                $rules[$ru['level']] = $ru;
            }
        }

        if ($subject_list) {
            /**@var $items array 格式化数组id */
            foreach ($subject_list as $value) {
                if (isset($goods[$value['id']])) {
                    $level = 1;
                    if (isset($rules[$level]) && ($goods[$value['id']]['num'] > $rules[$level]['up_num']) && ($this->user_info['points'] > $rules[$level]['up_point'])) {
                        $value['is_update'] = 1;
                    }
                } else {
                    $value['is_update'] = 0;
                }
                $value['level']      = 0;
                $items[$value['id']] = $value;
            }

            foreach ($user_level as $item) {
                if (isset($goods[$item['subject_id']])) {
                    $level = (int)$item['level'] + 1;
                    if (isset($rules[$level]) && ($goods[$item['subject_id']]['num'] > $rules[$level]['up_num']) && ($this->user_info['points'] > $rules[$level]['up_point'])) {
                        $items[$item['subject_id']]['is_update'] = 1;
                    } else {
                        $items[$item['subject_id']]['is_update'] = 0;
                    }
                }
                if (isset($items[$item['subject_id']])) {
                    $items[$item['subject_id']]['level'] = $item['level'];
                } else {
                    $items[$item['subject_id']]['level'] = 0;
                }
            }
            $list = tree($items);
            return $this->json_success('ok', $list);
        }
        return $this->json_error('暂无科目');
    }


    /**
     * 升级规则
     *
     * @throws \think\exception\DbException 数据库报错
     */
    public function updateRules()
    {
        $level      = input('post.level');
        $subject_id = input('post.subject_id');
        if (!$subject_id && isset($level)) {
            return $this->json_error('科目不存在');
        } else {
            //自己拥有的道具数量
            $prop = Db::name('prop p')
                      ->field('num')
                      ->where('subject_id', $subject_id)
                      ->join('user_goods g', 'g.target_id=p.id')
                      ->where('g.target_type', 2)
                      ->where('p.type', 4)
                      ->where('user_id', $this->user_info['id'])
                      ->find();
            //规则当前规则,和下一级规则
            $levelArr = Db::name('knowledge_up_rule')
                          ->field('up_num,up_point,reward_scale,level')
                          ->whereIn('level', [
                              $level,
                              $level + 1
                          ])
                          ->limit(2)
                          ->select();
            $temps    = [];
            if (!$prop) {
                $prop['num'] = 0;
            }
            foreach ($levelArr as $temp) {
                if ($level == 0) {
                    $temps['old_reward_scale'] = 0;
                    $temps['level']            = 0;
                }
                if ($temp['level'] == $level) {

                    $temps['old_reward_scale'] = $temp['reward_scale'];
                    $temps['level']            = $temp['level'];
                } else {
                    $temps['self_num']     = $prop['num'];
                    $temps['next_level']   = $temp['level'];
                    $temps['reward_scale'] = $temp['reward_scale'];
                    $temps['up_num']       = $temp['up_num'];
                    $temps['up_point']     = $temp['up_point'];
                }
            }
            if ($temps) {
                return $this->json_success('ok', $temps);
            }
        }
        return $this->json_error('暂无资料');
    }

    /**
     * 升级科目
     *
     * @param  int $level      级别
     * @param  int $subject_id 科目id
     *
     * @throws \think\exception\DbException
     * @throws \Exception
     */
    public function updateSubject($level = 0, $subject_id = 0)
    {
        //自己拥有的道具数量
        $prop = Db::name('prop p')
                  ->field('num,g.id,g.target_id,g.target_type')
                  ->where('subject_id', $subject_id)
                  ->join('user_goods g', 'g.target_id=p.id')
                  ->where('g.target_type', 2)
                  ->where('p.type', 4)
                  ->where('user_id', $this->user_info['id'])
                  ->find();


        //规则
        $rule_table = Db::name('knowledge_up_rule');
        $levels     = $rule_table->field('up_num,up_point,reward_scale,level')
                                 ->where('level', $level)
                                 ->find();
        if (($this->user_info['points'] - $levels['up_point']) > 0) {
            if (!$prop) {
                $prop['num'] = 0;
            }
            Db::startTrans();
            try {

                $num = (int)$prop['num'] - (int)$levels['up_num'];
                if ($num >= 0) {
                    Db::name('user_goods')
                      ->where('id', $prop['id'])
                      ->update(['num' => $num]);
                    $res = Db::name('user_knowledge_up')
                             ->where([
                                         'subject_id' => $subject_id,
                                         'user_id'    => $this->user_info['id']
                                     ])
                             ->find();
                    if ($res) {
                        Db::name('user_knowledge_up')
                          ->where([
                                      'subject_id' => $subject_id,
                                      'user_id'    => $this->user_info['id']
                                  ])
                          ->setInc('level');
                    } else {
                        $data = [
                            'user_id'     => $this->user_info['id'],
                            'subject_id'  => $subject_id,
                            'level'       => 1,
                            'update_time' => time()
                        ];
                        Db::name('user_knowledge_up')
                          ->insert($data);
                    }
                    Db::name('points_log')
                      ->insert([
                                   'user_id'     => $this->user_info['id'],
                                   'user_name'   => $this->user_info['display_name'],
                                   'points'      => '-'.$levels['up_point'],
                                   'remark'      => '科目升级扣除',
                                   'stage'       => 'sub',
                                   'create_time' => time(),
                                   'target_id'   => $prop['target_id'],
                                   'target_type' => $prop['target_type']
                               ]);
                    Db::name('reward_log')
                      ->insert([
                                   'user_id'     => $this->user_info['id'],
                                   'user_name'   => $this->user_info['display_name'],
                                   'remark'      => '科目升级',
                                   'stage'       => 'sub',
                                   'create_time' => time(),
                                   'target_id'   => $prop['target_id'],
                                   'target_type' => $prop['target_type']
                               ]);

                    Db::name("user")
                      ->where("id", $this->user_info['id'])
                      ->update(['points' => $this->user_info['points'] - $levels['up_point']]);
                    Db::commit();
                    return $this->json_success('升级成功');
                } else {
                    return $this->json_error('知识书不足,请购买');
                }
            } catch (\Exception $e) {
                Db::rollback();
            }
        }else{
            return $this->json_error('金币不足');
        }
        return $this->json_error('升级失败');
    }
}